<?php

namespace app\common\model;

use app\common\model\order\Goods;
use app\common\model\user\Address;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{




    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'paytime_text',
        'status_text',
        'canceltime_text',
        'taketime_text',
        'pay_type_text',
        'qx_time',
    ];

    public function getQxTimeAttr($value, $data)
    {
        $time = $data['createtime'] + 1800 - time();
        return $time > 0 ? $time : 0;
    }


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '-1' => __('Status -1')];
    }

    public function getPayTypeList()
    {
        return ['1' => __('Pay_type 1'), '2' => __('Pay_type 2')];
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function info()
    {
        return $this->hasMany('app\common\model\order\Goods', 'order_id', 'id');
    }

    public function address()
    {
        return $this->belongsTo('app\common\model\user\Address', 'address_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function yuOrder($array)
    {
        extract($array);
        
        try {
            //合计金额
            $data['total_money'] = $data['pay_money'] = array_sum(array_column($goods, 'totalMoney'));
            //合计返还积分
            $data['total_points'] = array_sum(array_column($goods, 'totalPoints'));
            $data['total'] = array_sum(array_column($goods, 'num'));
            $addressInfo = [];
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get([$address_id]);
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($uid);
                if ($addressInfo) {
                    $data['addressInfo'] = $addressInfo;
                    $data['address_id']  = $addressInfo['id'];
                }
            }
            $data['goodsList'] = $goods;
            return $data;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    public  function addData($data,  $uid)
    {
        $list = $data['goodsList'];
        $addressInfo = [];
        if ($data['addressInfo']) {
            $addressInfo = $data['addressInfo'];
        }
        $array = [
            'user_id' => $uid,
            'total_money' =>  $data['total_money'],
            'total_points' =>  $data['total_points'],
            'total' =>  $data['total'],
            'pay_money' =>  $data['total_money'],
            'sn' => sn('order', 'sn', 'NO'),
            'address_id' => $data['address_id'],
            'consignee' => $addressInfo['contact'] ?? '',
            'phone' => $addressInfo['telephone'] ?? '',
            'address' => $addressInfo['city'] . $addressInfo['address'],
        ];

        $res = $this->allowField(true)->save($array);
        if ($res) {
            $info = [];
            foreach ($list as $v) {
                $info[] = [
                    'order_id' => $this->id,
                    'goods_id' => $v['goods_id'],
                    'goods_num' => $v['num'],
                    'goods_name' => $v->goods->title,
                    'goods_price' =>$v->goods->price,
                    'points' => $v['totalPoints'],
                    'total_price' => $v['totalMoney'],
                    'image' => $v->goods->image,
                ];
            }

            $infos = new Goods();
            $infos->isUpdate(false)->saveAll($info);
        }
        return $this;
    }

    public function moreOrder($array)
    {
        extract($array);
        try {
            //合计金额  //实际支付金额
            $data['total_points'] =  $goods->totalPoint;
            $data['total_money'] =  $goods->totalMoney;
            $data['state'] =  $goods->state;
            $data['pay_money'] =  bcsub($pay_money, $discount_amount, 2);
            $data['total'] = array_sum(array_column($goods, 'goods_num'));
            $addressInfo = [];
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get([$address_id]);
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($uid);
                if ($addressInfo) {
                    $data['addressInfo'] = $addressInfo;
                    $data['address_id']  = $addressInfo['id'];
                }
            }
            $data['goodsList'] = $goods;
            return $data;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
}
